package com.geovis.emergency.spd.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.geovis.common.core.api.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Log4j2
public class SignatureUtil {

    @Value("${third.appId}")
    private String appId;
    @Value("${third.appSecret}")
    private String appSecret;

    private static final Long TIMEOUT=600L;

    /**
     * 验签
     * @param
     * @param
     */
    public boolean verification(String sign, String timestamp, Result result){
        long time = DateUtil.currentSeconds();
        long l = Long.parseLong(timestamp);
        if(Math.abs(time - l) >TIMEOUT){
            result.setCode(401);
            result.setMessage("签名已经过期了!");
            return false;
        }
        boolean verification = getResult(sign,timestamp);
        if(!verification){
            result.setCode(401);
            result.setMessage("无效签名，请检查后再试!");
            return false;
        }
        return true;
    }



    /**
     * 获取签名
     * @return
     */
    public boolean getResult(String sign, String timestamp){
        String signValue = SecureUtil.md5(appId.concat(appSecret).concat(timestamp));
        if(sign.equals(signValue)){
            return true;
        }
        return false;
    }


}
